<html><head>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>26.&nbsp;Task Execution and Scheduling</title><link rel="stylesheet" href="css/stylesheet.css" type="text/css"><meta name="generator" content="DocBook XSL Stylesheets V1.74.0"><link rel="home" href="index.html" title="Reference Documentation"><link rel="up" href="spring-integration.html" title="Part&nbsp;VI.&nbsp;Integration"><link rel="prev" href="mail.html" title="25.&nbsp;Email"><link rel="next" href="dynamic-language.html" title="27.&nbsp;Dynamic language support"><!--Begin Google Analytics code--><script type="text/javascript">
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		</script><script type="text/javascript">
			var pageTracker = _gat._getTracker("UA-2728886-3");
			pageTracker._setDomainName("none");
			pageTracker._setAllowLinker(true);
			pageTracker._trackPageview();
		</script><!--End Google Analytics code--></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">26.&nbsp;Task Execution and Scheduling</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="mail.html">Prev</a>&nbsp;</td><th width="60%" align="center">Part&nbsp;VI.&nbsp;Integration</th><td width="20%" align="right">&nbsp;<a accesskey="n" href="dynamic-language.html">Next</a></td></tr></table><hr></div><div class="chapter" lang="en"><div class="titlepage"><div><div><h2 class="title"><a name="scheduling"></a>26.&nbsp;Task Execution and Scheduling</h2></div></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-introduction"></a>26.1&nbsp;Introduction</h2></div></div></div><p>The Spring Framework provides abstractions for asynchronous
    execution and scheduling of tasks with the
    <code class="interfacename">TaskExecutor</code> and
    <code class="interfacename">TaskScheduler</code> interfaces, respectively.
    Spring also features implementations of those interfaces that support
    thread pools or delegation to CommonJ within an application server
    environment. Ultimately the use of these implementations behind the common
    interfaces abstracts away the differences between Java SE 5, Java SE 6 and
    Java EE environments.</p><p>Spring also features integration classes for supporting scheduling
    with the <code class="classname">Timer</code>, part of the JDK since 1.3, and the
    Quartz Scheduler (<a class="ulink" href="http://www.opensymphony.com/quartz/" target="_top">http://www.opensymphony.com/quartz/</a>). Both of those
    schedulers are set up using a <code class="interfacename">FactoryBean</code>
    with optional references to <code class="classname">Timer</code> or
    <code class="classname">Trigger</code> instances, respectively. Furthermore, a
    convenience class for both the Quartz Scheduler and the
    <code class="classname">Timer</code> is available that allows you to invoke a
    method of an existing target object (analogous to the normal
    <code class="classname">MethodInvokingFactoryBean</code> operation).</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-task-executor"></a>26.2&nbsp;The Spring <code class="interfacename">TaskExecutor</code>
    abstraction</h2></div></div></div><p>Spring 2.0 introduces a new abstraction for dealing with executors.
    Executors are the Java 5 name for the concept of thread pools. The
    "executor" naming is due to the fact that there is no guarantee that the
    underlying implementation is actually a pool; an executor may be
    single-threaded or even synchronous. Spring's abstraction hides
    implementation details between Java SE 1.4, Java SE 5 and Java EE
    environments.</p><p>Spring's <code class="interfacename">TaskExecutor</code> interface is
    identical to the <code class="classname">java.util.concurrent.Executor</code>
    interface. In fact, its primary reason for existence is to abstract away
    the need for Java 5 when using thread pools. The interface has a single
    method <code class="classname">execute(Runnable task)</code> that accepts a task
    for execution based on the semantics and configuration of the thread
    pool.</p><p>The <code class="interfacename">TaskExecutor</code> was originally
    created to give other Spring components an abstraction for thread pooling
    where needed. Components such as the
    <code class="classname">ApplicationEventMulticaster</code>, JMS's
    <code class="classname">AbstractMessageListenerContainer</code>, and Quartz
    integration all use the <code class="interfacename">TaskExecutor</code>
    abstraction to pool threads. However, if your beans need thread pooling
    behavior, it is possible to use this abstraction for your own
    needs.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-task-executor-types"></a>26.2.1&nbsp;<code class="interfacename">TaskExecutor</code> types</h3></div></div></div><p>There are a number of pre-built implementations of
      <code class="interfacename">TaskExecutor</code> included with the Spring
      distribution. In all likelihood, you shouldn't ever need to implement
      your own.</p><div class="itemizedlist"><ul type="disc"><li><p><code class="classname">SimpleAsyncTaskExecutor</code></p><p>This implementation does not reuse any threads, rather it
          starts up a new thread for each invocation. However, it does support
          a concurrency limit which will block any invocations that are over
          the limit until a slot has been freed up. If you're looking for true
          pooling, keep scrolling further down the page.</p></li><li><p><a name="syncTaskExecutor"></a><code class="classname">SyncTaskExecutor</code></p><p>This implementation doesn't execute invocations
          asynchronously. Instead, each invocation takes place in the calling
          thread. It is primarily used in situations where multithreading
          isn't necessary such as simple test cases.</p></li><li><p><a name="concurrentTaskExecutor"></a><code class="classname">ConcurrentTaskExecutor</code></p><p>This implementation is a wrapper for a Java 5
          <code class="classname">java.util.concurrent.Executor</code>. There is an
          alternative, <code class="classname">ThreadPoolTaskExecutor</code>, that
          exposes the <code class="classname">Executor</code> configuration parameters
          as bean properties. It is rare to need to use the
          <code class="classname">ConcurrentTaskExecutor</code> but if the <a class="link" href="scheduling.html#threadPoolTaskExecutor"><code class="classname">ThreadPoolTaskExecutor</code></a>
          isn't robust enough for your needs, the
          <code class="classname">ConcurrentTaskExecutor</code> is an
          alternative.</p></li><li><p><a name="simpleThreadPoolTaskExecutor"></a><code class="classname">SimpleThreadPoolTaskExecutor</code></p><p>This implementation is actually a subclass of Quartz's
          <code class="classname">SimpleThreadPool</code> which listens to Spring's
          lifecycle callbacks. This is typically used when you have a thread
          pool that may need to be shared by both Quartz and non-Quartz
          components.</p></li><li><p><a name="threadPoolTaskExecutor"></a><code class="classname">ThreadPoolTaskExecutor</code></p><div class="sidebar"><p class="title"><b></b></p><p>It is not possible to use any backport or alternate versions
            of the <code class="classname">java.util.concurrent</code> package with
            this implementation. Both Doug Lea's and Dawid Kurzyniec's
            implementations use different package structures which will
            prevent them from working correctly.</p></div><p>This implementation can only be used in a Java 5 environment
          but is also the most commonly used one in that environment. It
          exposes bean properties for configuring a
          <code class="classname">java.util.concurrent.ThreadPoolExecutor</code> and
          wraps it in a <code class="interfacename">TaskExecutor</code>. If you
          need something advanced such as a
          <code class="classname">ScheduledThreadPoolExecutor</code>, it is
          recommended that you use a <a class="link" href="scheduling.html#concurrentTaskExecutor"><code class="classname">ConcurrentTaskExecutor</code></a>
          instead.</p></li><li><p><code class="classname">TimerTaskExecutor</code></p><p>This implementation uses a single
          <code class="classname">TimerTask</code> as its backing implementation. It's
          different from the <a class="link" href="scheduling.html#syncTaskExecutor"><code class="classname">SyncTaskExecutor</code></a>
          in that the method invocations are executed in a separate thread,
          although they are synchronous in that thread.</p></li><li><p><code class="classname">WorkManagerTaskExecutor</code></p><div class="sidebar"><p class="title"><b></b></p><p>CommonJ is a set of specifications jointly developed between
            BEA and IBM. These specifications are not Java EE standards, but
            are standard across BEA's and IBM's Application Server
            implementations.</p></div><p>This implementation uses the CommonJ WorkManager as its
          backing implementation and is the central convenience class for
          setting up a CommonJ WorkManager reference in a Spring context.
          Similar to the <a class="link" href="scheduling.html#simpleThreadPoolTaskExecutor"><code class="classname">SimpleThreadPoolTaskExecutor</code></a>,
          this class implements the WorkManager interface and therefore can be
          used directly as a WorkManager as well.</p></li></ul></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-task-executor-usage"></a>26.2.2&nbsp;Using a <code class="interfacename">TaskExecutor</code></h3></div></div></div><p>Spring's <code class="interfacename">TaskExecutor</code>
      implementations are used as simple JavaBeans. In the example below, we
      define a bean that uses the
      <code class="classname">ThreadPoolTaskExecutor</code> to asynchronously print
      out a set of messages.</p><pre class="programlisting"><span class="hl-keyword">import</span> org.springframework.core.task.TaskExecutor;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> TaskExecutorExample {

  <span class="hl-keyword">private</span> <span class="hl-keyword">class</span> MessagePrinterTask <span class="hl-keyword">implements</span> Runnable {

    <span class="hl-keyword">private</span> String message;

    <span class="hl-keyword">public</span> MessagePrinterTask(String message) {
      <span class="hl-keyword">this</span>.message = message;
    }

    <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> run() {
      System.out.println(message);
    }

  }

  <span class="hl-keyword">private</span> TaskExecutor taskExecutor;

  <span class="hl-keyword">public</span> TaskExecutorExample(TaskExecutor taskExecutor) {
    <span class="hl-keyword">this</span>.taskExecutor = taskExecutor;
  }

  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> printMessages() {
    <span class="hl-keyword">for</span>(<span class="hl-keyword">int</span> i = 0; i &lt; 25; i++) {
      taskExecutor.execute(<span class="hl-keyword">new</span> MessagePrinterTask(<span class="hl-string">"Message"</span> + i));
    }
  }
}</pre><p>As you can see, rather than retrieving a thread from the pool and
      executing yourself, you add your <code class="classname">Runnable</code> to the
      queue and the <code class="interfacename">TaskExecutor</code> uses its
      internal rules to decide when the task gets executed.</p><p>To configure the rules that the
      <code class="interfacename">TaskExecutor</code> will use, simple bean
      properties have been exposed.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"taskExecutor"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"corePoolSize"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"5"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"maxPoolSize"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"10"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"queueCapacity"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"25"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"taskExecutorExample"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"TaskExecutorExample"</span>&gt;
  &lt;<span class="hl-tag">constructor-arg</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"taskExecutor"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-task-scheduler"></a>26.3&nbsp;The Spring <code class="interfacename">TaskScheduler</code>
    abstraction</h2></div></div></div><p>In addition to the <code class="interfacename">TaskExecutor</code>
    abstraction, Spring 3.0 introduces a
    <code class="interfacename">TaskScheduler</code> with a variety of methods for
    scheduling tasks to run at some point in the future.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> TaskScheduler {

    ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, <span class="hl-keyword">long</span> period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, <span class="hl-keyword">long</span> period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, <span class="hl-keyword">long</span> delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, <span class="hl-keyword">long</span> delay);

}</pre><p>The simplest method is the one named 'schedule' that takes a
    <code class="interfacename">Runnable</code> and <code class="classname">Date</code>
    only. That will cause the task to run once after the specified time. All
    of the other methods are capable of scheduling tasks to run repeatedly.
    The fixed-rate and fixed-delay methods are for simple, periodic execution,
    but the method that accepts a Trigger is much more flexible.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-trigger-interface"></a>26.3.1&nbsp;The <code class="interfacename">Trigger</code> interface</h3></div></div></div><p>The <code class="interfacename">Trigger</code> interface is
      essentially inspired by JSR-236, which, as of Spring 3.0, has not yet
      been officially implemented. The basic idea of the
      <code class="interfacename">Trigger</code> is that execution times may be
      determined based on past execution outcomes or even arbitrary
      conditions. If these determinations do take into account the outcome of
      the preceding execution, that information is available within a
      <code class="interfacename">TriggerContext</code>. The
      <code class="interfacename">Trigger</code> interface itself is quite
      simple:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> Trigger {

    Date nextExecutionTime(TriggerContext triggerContext);

}</pre><p>As you can see, the <code class="interfacename">TriggerContext</code>
      is the most important part. It encapsulates all of the relevant data,
      and is open for extension in the future if necessary. The
      <code class="interfacename">TriggerContext</code> is an interface (a
      <code class="classname">SimpleTriggerContext</code> implementation is used by
      default). Here you can see what methods are available for
      <code class="interfacename">Trigger</code> implementations.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">interface</span> TriggerContext {

    Date lastScheduledExecutionTime();

    Date lastActualExecutionTime();

    Date lastCompletionTime();

}</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-trigger-implementations"></a>26.3.2&nbsp;<code class="interfacename">Trigger</code> implementations</h3></div></div></div><p>Spring provides two implementations of the
      <code class="interfacename">Trigger</code> interface. The most interesting
      one is the <code class="classname">CronTrigger</code>. It enables the scheduling
      of tasks based on cron expressions. For example the following task is
      being scheduled to run 15 minutes past each hour but only during the
      9-to-5 "business hours" on weekdays.</p><pre class="programlisting">scheduler.schedule(task, <span class="hl-keyword">new</span> CronTrigger(<span class="hl-string">"* 15 9-17 * * MON-FRI"</span>));</pre><p>The other out-of-the-box implementation is a
      <code class="classname">PeriodicTrigger</code> that accepts a fixed period, an
      optional initial delay value, and a boolean to indicate whether the
      period should be interpreted as a fixed-rate or a fixed-delay. Since the
      <code class="interfacename">TaskScheduler</code> interface already defines
      methods for scheduling tasks at a fixed-rate or with a fixed-delay,
      those methods should be used directly whenever possible. The value of
      the <code class="classname">PeriodicTrigger</code> implementation is that it can
      be used within components that rely on the
      <code class="interfacename">Trigger</code> abstraction. For example, it may
      be convenient to allow periodic triggers, cron-based triggers, and even
      custom trigger implementations to be used interchangeably. Such a
      component could take advantage of dependency injection so that such
      <code class="interfacename">Triggers</code> could be configured
      externally.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-task-scheduler-implementations"></a>26.3.3&nbsp;<code class="interfacename">TaskScheduler</code>
      implementations</h3></div></div></div><p>As with Spring's <code class="interfacename">TaskExecutor</code>
      abstraction, the primary benefit of the
      <code class="interfacename">TaskScheduler</code> is that code relying on
      scheduling behavior need not be coupled to a particular scheduler
      implementation. The flexibility this provides is particularly relevant
      when running within Application Server environments where threads should
      not be created directly by the application itself. For such cases,
      Spring provides a <code class="classname">TimerManagerTaskScheduler</code> that
      delegates to a CommonJ TimerManager instance, typically configured with
      a JNDI-lookup.</p><p>A simpler alternative, the
      <code class="classname">ThreadPoolTaskScheduler</code>, can be used whenever
      external thread management is not a requirement. Internally, it
      delegates to a <code class="interfacename">ScheduledExecutorService</code>
      instance. <code class="classname">ThreadPoolTaskScheduler</code> actually
      implements Spring's <code class="interfacename">TaskExecutor</code>
      interface as well, so that a single instance can be used for
      asynchronous execution <span class="emphasis"><em>as soon as possible</em></span> as well
      as scheduled, and potentially recurring, executions.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-task-namespace"></a>26.4&nbsp;The Task Namespace</h2></div></div></div><p>Beginning with Spring 3.0, there is an XML namespace for configuring
    <code class="interfacename">TaskExecutor</code> and
    <code class="interfacename">TaskScheduler</code> instances. It also provides a
    convenient way to configure tasks to be scheduled with a trigger.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-task-namespace-scheduler"></a>26.4.1&nbsp;The 'scheduler' element</h3></div></div></div><p>The following element will create a
      <code class="classname">ThreadPoolTaskScheduler</code> instance with the
      specified thread pool size.</p><pre class="programlisting">&lt;<span class="hl-tag">task:scheduler</span> <span class="hl-attribute">id</span>=<span class="hl-value">"scheduler"</span> <span class="hl-attribute">pool-size</span>=<span class="hl-value">"10"</span>/&gt;</pre><p>The value provided for the 'id' attribute will be used as the
      prefix for thread names within the pool. The 'scheduler' element is
      relatively straightforward. If you do not provide a 'pool-size'
      attribute, the default thread pool will only have a single thread. There
      are no other configuration options for the scheduler.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-task-namespace-executor"></a>26.4.2&nbsp;The 'executor' element</h3></div></div></div><p>The following will create a
      <code class="classname">ThreadPoolTaskExecutor</code> instance: </p><pre class="programlisting">&lt;<span class="hl-tag">task:executor</span> <span class="hl-attribute">id</span>=<span class="hl-value">"executor"</span> <span class="hl-attribute">pool-size</span>=<span class="hl-value">"10"</span>/&gt;</pre><p>As with the scheduler above, the value provided for the 'id'
      attribute will be used as the prefix for thread names within the pool.
      As far as the pool size is concerned, the 'executor' element supports
      more configuration options than the 'scheduler' element. For one thing,
      the thread pool for a <code class="classname">ThreadPoolTaskExecutor</code> is
      itself more configurable. Rather than just a single size, an executor's
      thread pool may have different values for the <span class="emphasis"><em>core</em></span>
      and the <span class="emphasis"><em>max</em></span> size. If a single value is provided
      then the executor will have a fixed-size thread pool (the core and max
      sizes are the same). However, the 'executor' element's 'pool-size'
      attribute also accepts a range in the form of "min-max". </p><pre class="programlisting">&lt;<span class="hl-tag">task:executor</span> <span class="hl-attribute">id</span>=<span class="hl-value">"executorWithPoolSizeRange"</span>
	               <span class="hl-attribute">pool-size</span>=<span class="hl-value">"5-25"</span>
	               <span class="hl-attribute">queue-capacity</span>=<span class="hl-value">"100"</span>/&gt;</pre><p>As you can see from that configuration, a 'queue-capacity' value
      has also been provided. The configuration of the thread pool should also
      be considered in light of the executor's queue capacity. For the full
      description of the relationship between pool size and queue capacity,
      consult the documentation for <a class="ulink" href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html" target="_top">ThreadPoolExecutor</a>.
      The main idea is that when a task is submitted, the executor will first
      try to use a free thread if the number of active threads is currently
      less than the core size. If the core size has been reached, then the
      task will be added to the queue as long as its capacity has not yet been
      reached. Only then, if the queue's capacity <span class="emphasis"><em>has</em></span>
      been reached, will the executor create a new thread beyond the core
      size. If the max size has also been reached, then the executor will
      reject the task.</p><p>By default, the queue is <span class="emphasis"><em>unbounded</em></span>, but this
      is rarely the desired configuration, because it can lead to
      <code class="classname">OutOfMemoryErrors</code> if enough tasks are added to
      that queue while all pool threads are busy. Furthermore, if the queue is
      unbounded, then the max size has no effect at all. Since the executor
      will always try the queue before creating a new thread beyond the core
      size, a queue must have a finite capacity for the thread pool to grow
      beyond the core size (this is why a <span class="emphasis"><em>fixed size</em></span> pool
      is the only sensible case when using an unbounded queue).</p><p>In a moment, we will review the effects of the keep-alive setting
      which adds yet another factor to consider when providing a pool size
      configuration. First, let's consider the case, as mentioned above, when
      a task is rejected. By default, when a task is rejected, a thread pool
      executor will throw a <code class="classname">TaskRejectedException</code>.
      However, the rejection policy is actually configurable. The exception is
      thrown when using the default rejection policy which is the
      <code class="classname">AbortPolicy</code> implementation. For applications
      where some tasks can be skipped under heavy load, either the
      <code class="classname">DiscardPolicy</code> or
      <code class="classname">DiscardOldestPolicy</code> may be configured instead.
      Another option that works well for applications that need to throttle
      the submitted tasks under heavy load is the
      <code class="classname">CallerRunsPolicy</code>. Instead of throwing an
      exception or discarding tasks, that policy will simply force the thread
      that is calling the submit method to run the task itself. The idea is
      that such a caller will be busy while running that task and not able to
      submit other tasks immediately. Therefore it provides a simple way to
      throttle the incoming load while maintaining the limits of the thread
      pool and queue. Typically this allows the executor to "catch up" on the
      tasks it is handling and thereby frees up some capacity on the queue, in
      the pool, or both. Any of these options can be chosen from an
      enumeration of values available for the 'rejection-policy' attribute on
      the 'executor' element.</p><pre class="programlisting">&lt;<span class="hl-tag">task:executor</span> <span class="hl-attribute">id</span>=<span class="hl-value">"executorWithCallerRunsPolicy"</span>
               <span class="hl-attribute">pool-size</span>=<span class="hl-value">"5-25"</span>
               <span class="hl-attribute">queue-capacity</span>=<span class="hl-value">"100"</span>
               <span class="hl-attribute">rejection-policy</span>=<span class="hl-value">"CALLER_RUNS"</span>/&gt;</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-task-namespace-scheduled-tasks"></a>26.4.3&nbsp;The 'scheduled-tasks' element</h3></div></div></div><p>The most powerful feature of Spring's task namespace is the
      support for configuring tasks to be scheduled within a Spring
      Application Context. This follows an approach similar to other
      "method-invokers" in Spring, such as that provided by the JMS namespace
      for configuring Message-driven POJOs. Basically a "ref" attribute can
      point to any Spring-managed object, and the "method" attribute provides
      the name of a method to be invoked on that object. Here is a simple
      example.</p><pre class="programlisting">&lt;<span class="hl-tag">task:scheduled-tasks</span> <span class="hl-attribute">scheduler</span>=<span class="hl-value">"myScheduler"</span>&gt;
    &lt;<span class="hl-tag">task:scheduled</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"someObject"</span> <span class="hl-attribute">method</span>=<span class="hl-value">"someMethod"</span> <span class="hl-attribute">fixed-delay</span>=<span class="hl-value">"5000"</span>/&gt;
&lt;<span class="hl-tag">/task:scheduled-tasks</span>&gt;

&lt;<span class="hl-tag">task:scheduler</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myScheduler"</span> <span class="hl-attribute">pool-size</span>=<span class="hl-value">"10"</span>/&gt;</pre><p>As you can see, the scheduler is referenced by the outer element,
      and each individual task includes the configuration of its trigger
      metadata. In the preceding example, that metadata defines a periodic
      trigger with a fixed delay. It could also be configured with a
      "fixed-rate", or for more control, a "cron" attribute could be provided
      instead. Here's an example featuring these other options.</p><pre class="programlisting">&lt;<span class="hl-tag">task:scheduled-tasks</span> <span class="hl-attribute">scheduler</span>=<span class="hl-value">"myScheduler"</span>&gt;
    &lt;<span class="hl-tag">task:scheduled</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"someObject"</span> <span class="hl-attribute">method</span>=<span class="hl-value">"someMethod"</span> <span class="hl-attribute">fixed-rate</span>=<span class="hl-value">"5000"</span>/&gt;
    &lt;<span class="hl-tag">task:scheduled</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"anotherObject"</span> <span class="hl-attribute">method</span>=<span class="hl-value">"anotherMethod"</span> <span class="hl-attribute">cron</span>=<span class="hl-value">"*/5 * * * * MON-FRI"</span>/&gt;
&lt;<span class="hl-tag">/task:scheduled-tasks</span>&gt;

&lt;<span class="hl-tag">task:scheduler</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myScheduler"</span> <span class="hl-attribute">pool-size</span>=<span class="hl-value">"10"</span>/&gt;</pre></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-annotation-support"></a>26.5&nbsp;Annotation Support for Scheduling and Asynchronous
    Execution</h2></div></div></div><p>Spring 3.0 also adds annotation support for both task scheduling and
    asynchronous method execution.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-annotation-support-scheduled"></a>26.5.1&nbsp;The @Scheduled Annotation</h3></div></div></div><p>The @Scheduled annotation can be added to a method along with
      trigger metadata. For example, the following method would be invoked
      every 5 seconds with a fixed delay, meaning that the period will be
      measured from the completion time of each preceding invocation.</p><pre class="programlisting">@Scheduled(fixedDelay=5000)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> doSomething() {
    <span class="hl-comment">// something that should execute periodically</span>
}</pre><p>If a fixed rate execution is desired, simply change the property
      name specified within the annotation. The following would be executed
      every 5 seconds measured between the successive start times of each
      invocation.</p><pre class="programlisting">@Scheduled(fixedRate=5000)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> doSomething() {
    <span class="hl-comment">// something that should execute periodically</span>
}</pre><p>If simple periodic scheduling is not expressive enough, then a
      cron expression may be provided. For example, the following will only
      execute on weekdays.</p><pre class="programlisting">@Scheduled(cron=<span class="hl-string">"*/5 * * * * MON-FRI"</span>)
<span class="hl-keyword">public</span> <span class="hl-keyword">void</span> doSomething() {
    <span class="hl-comment">// something that should execute on weekdays only</span>
}</pre><p>Notice that the methods to be scheduled must have void returns and
      must not expect any arguments. If the method needs to interact with
      other objects from the Application Context, then those would typically
      have been provided through dependency injection.</p><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>Make sure that you are not initializing multiple instances of
        the same @Scheduled annotation class at runtime, unless you do want to
        schedule callbacks to each such instance. Related to this, make sure
        that you do not use @Configurable on bean classes which are annotated
        with @Scheduled and registered as regular Spring beans with the
        container: You would get double initialization otherwise, once through
        the container and once through the @Configurable aspect, with the
        consequence of each @Scheduled method being invoked twice.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-annotation-support-async"></a>26.5.2&nbsp;The @Async Annotation</h3></div></div></div><p>The <code class="interfacename">@Async</code> annotation can be
      provided on a method so that invocation of that method will occur
      asynchronously. In other words, the caller will return immediately upon
      invocation and the actual execution of the method will occur in a task
      that has been submitted to a Spring
      <code class="interfacename">TaskExecutor</code>. In the simplest case, the
      annotation may be applied to a <code class="literal">void</code>-returning
      method.</p><pre class="programlisting">@Async
<span class="hl-keyword">void</span> doSomething() {
    <span class="hl-comment">// this will be executed asynchronously</span>
}</pre><p>Unlike the methods annotated with the
      <code class="interfacename">@Scheduled</code> annotation, these methods can
      expect arguments, because they will be invoked in the "normal" way by
      callers at runtime rather than from a scheduled task being managed by
      the container. For example, the following is a legitimate application of
      the <code class="interfacename">@Async</code> annotation.</p><pre class="programlisting">@Async
<span class="hl-keyword">void</span> doSomething(String s) {
    <span class="hl-comment">// this will be executed asynchronously</span>
}</pre><p>Even methods that return a value can be invoked asynchronously.
      However, such methods are required to have a
      <code class="interfacename">Future</code> typed return value. This still
      provides the benefit of asynchronous execution so that the caller can
      perform other tasks prior to calling <code class="methodname">get()</code> on
      that Future.</p><pre class="programlisting">@Async
Future&lt;String&gt; returnSomething(<span class="hl-keyword">int</span> i) {
    <span class="hl-comment">// this will be executed asynchronously</span>
}</pre><p><code class="interfacename">@Async</code> can not be used in
      conjunction with lifecycle callbacks such as
      <code class="interfacename">@PostConstruct</code>. To asynchonously
      initialize Spring beans you currently have to use a separate
      initializing Spring bean that invokes the
      <code class="interfacename">@Async</code> annotated method on the target
      then.</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SampleBeanImpl <span class="hl-keyword">implements</span> SampleBean {

  @Async
  <span class="hl-keyword">void</span> doSomething() { &#8230; }
}


<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> SampleBeanInititalizer {

  <span class="hl-keyword">private</span> <span class="hl-keyword">final</span> SampleBean bean;

  <span class="hl-keyword">public</span> SampleBeanInitializer(SampleBean bean) {
    <span class="hl-keyword">this</span>.bean = bean;
  }

  @PostConstruct
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> initialize() {
    bean.doSomething();
  }
}</pre></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-annotation-support-namespace"></a>26.5.3&nbsp;The &lt;annotation-driven&gt; Element</h3></div></div></div><p>To enable both @Scheduled and @Async annotations, simply include
      the 'annotation-driven' element from the task namespace in your
      configuration.</p><pre class="programlisting">&lt;<span class="hl-tag">task:annotation-driven</span> <span class="hl-attribute">executor</span>=<span class="hl-value">"myExecutor"</span> <span class="hl-attribute">scheduler</span>=<span class="hl-value">"myScheduler"</span>/&gt;

&lt;<span class="hl-tag">task:executor</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myExecutor"</span> <span class="hl-attribute">pool-size</span>=<span class="hl-value">"5"</span>/&gt;

&lt;<span class="hl-tag">task:scheduler</span> <span class="hl-attribute">id</span>=<span class="hl-value">"myScheduler"</span> <span class="hl-attribute">pool-size</span>=<span class="hl-value">"10"</span>/&gt;}</pre><p>Notice that an executor reference is provided for handling those
      tasks that correspond to methods with the @Async annotation, and the
      scheduler reference is provided for managing those methods annotated
      with @Scheduled.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-quartz"></a>26.6&nbsp;Using the OpenSymphony Quartz Scheduler</h2></div></div></div><p>Quartz uses <code class="classname">Trigger</code>,
    <code class="classname">Job</code> and <code class="classname">JobDetail</code> objects to
    realize scheduling of all kinds of jobs. For the basic concepts behind
    Quartz, have a look at <a class="ulink" href="http://www.opensymphony.com/quartz" target="_top">http://www.opensymphony.com/quartz</a>. For convenience
    purposes, Spring offers a couple of classes that simplify the usage of
    Quartz within Spring-based applications.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-quartz-jobdetail"></a>26.6.1&nbsp;Using the JobDetailBean</h3></div></div></div><p><code class="classname">JobDetail</code> objects contain all information
      needed to run a job. The Spring Framework provides a
      <code class="classname">JobDetailBean</code> that makes the
      <code class="classname">JobDetail</code> more of an actual JavaBean with
      sensible defaults. Let's have a look at an example:</p><pre class="programlisting">
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">name</span>=<span class="hl-value">"exampleJob"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.quartz.JobDetailBean"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"jobClass"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"example.ExampleJob"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"jobDataAsMap"</span>&gt;
    &lt;<span class="hl-tag">map</span>&gt;
      &lt;<span class="hl-tag">entry</span> <span class="hl-attribute">key</span>=<span class="hl-value">"timeout"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"5"</span> /&gt;
    &lt;<span class="hl-tag">/map</span>&gt;
  &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The job detail bean has all information it needs to run the job
      (<code class="classname">ExampleJob</code>). The timeout is specified in the job
      data map. The job data map is available through the
      <code class="classname">JobExecutionContext</code> (passed to you at execution
      time), but the <code class="classname">JobDetailBean</code> also maps the
      properties from the job data map to properties of the actual job. So in
      this case, if the <code class="classname">ExampleJob</code> contains a property
      named <code class="literal">timeout</code>, the
      <code class="classname">JobDetailBean</code> will automatically apply it:</p><pre class="programlisting"><span class="hl-keyword">package</span> example;

<span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleJob <span class="hl-keyword">extends</span> QuartzJobBean {

  <span class="hl-keyword">private</span> <span class="hl-keyword">int</span> timeout;
  
  <span class="hl-comment">/**
   * Setter called after the ExampleJob is instantiated
   * with the value from the JobDetailBean (5)
   */</span> 
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setTimeout(<span class="hl-keyword">int</span> timeout) {
    <span class="hl-keyword">this</span>.timeout = timeout;
  }
  
  <span class="hl-keyword">protected</span> <span class="hl-keyword">void</span> executeInternal(JobExecutionContext ctx) <span class="hl-keyword">throws</span> JobExecutionException {
      <span class="hl-comment">// do the actual work</span>
  }
}</pre><p>All additional settings from the job detail bean are of course
      available to you as well.</p><p><span class="emphasis"><em>Note: Using the <code class="literal">name</code> and
      <code class="literal">group</code> properties, you can modify the name and the
      group of the job, respectively. By default, the name of the job matches
      the bean name of the job detail bean (in the example above, this is
      <code class="literal">exampleJob</code>).</em></span></p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-quartz-method-invoking-job"></a>26.6.2&nbsp;Using the
      <code class="classname">MethodInvokingJobDetailFactoryBean</code></h3></div></div></div><p>Often you just need to invoke a method on a specific object. Using
      the <code class="classname">MethodInvokingJobDetailFactoryBean</code> you can do
      exactly this:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"jobDetail"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetObject"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"exampleBusinessObject"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetMethod"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"doIt"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The above example will result in the <code class="literal">doIt</code>
      method being called on the <code class="literal">exampleBusinessObject</code>
      method (see below):</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> ExampleBusinessObject {
  
  <span class="hl-comment">// properties and collaborators</span>
  
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> doIt() {
    <span class="hl-comment">// do the actual work</span>
  }
}</pre><pre class="programlisting">
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"exampleBusinessObject"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.ExampleBusinessObject"</span>/&gt;</pre><p>Using the
      <code class="classname">MethodInvokingJobDetailFactoryBean</code>, you don't
      need to create one-line jobs that just invoke a method, and you only
      need to create the actual business object and wire up the detail
      object.</p><p>By default, Quartz Jobs are stateless, resulting in the
      possibility of jobs interfering with each other. If you specify two
      triggers for the same <code class="classname">JobDetail</code>, it might be
      possible that before the first job has finished, the second one will
      start. If <code class="classname">JobDetail</code> classes implement the
      <code class="interfacename">Stateful</code> interface, this won't happen.
      The second job will not start before the first one has finished. To make
      jobs resulting from the
      <code class="classname">MethodInvokingJobDetailFactoryBean</code>
      non-concurrent, set the <code class="literal">concurrent</code> flag to
      <code class="literal">false</code>.</p><pre class="programlisting">
&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"jobDetail"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"</span>&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetObject"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"exampleBusinessObject"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetMethod"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"doIt"</span> /&gt;
  &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"concurrent"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"false"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"><table border="0" summary="Note"><tr><td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="images/note.gif"></td><th align="left">Note</th></tr><tr><td align="left" valign="top"><p>By default, jobs will run in a concurrent fashion.</p></td></tr></table></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-quartz-cron"></a>26.6.3&nbsp;Wiring up jobs using triggers and the
      <code class="classname">SchedulerFactoryBean</code></h3></div></div></div><p>We've created job details and jobs. We've also reviewed the
      convenience bean that allows you to invoke a method on a specific
      object. Of course, we still need to schedule the jobs themselves. This
      is done using triggers and a
      <code class="classname">SchedulerFactoryBean</code>. Several triggers are
      available within Quartz. Spring offers two subclassed triggers with
      convenient defaults: <code class="classname">CronTriggerBean</code> and
      <code class="classname">SimpleTriggerBean</code>.</p><p>Triggers need to be scheduled. Spring offers a
      <code class="classname">SchedulerFactoryBean</code> that exposes triggers to be
      set as properties. <code class="classname">SchedulerFactoryBean</code> schedules
      the actual jobs with those triggers.</p><p>Find below a couple of examples:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"simpleTrigger"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.quartz.SimpleTriggerBean"</span>&gt;
    &lt;<span class="hl-comment">!-- see the example of method invoking job above --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"jobDetail"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"jobDetail"</span> /&gt;
    &lt;<span class="hl-comment">!-- 10 seconds --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"startDelay"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"10000"</span> /&gt;
    &lt;<span class="hl-comment">!-- repeat every 50 seconds --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"repeatInterval"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"50000"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"cronTrigger"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.quartz.CronTriggerBean"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"jobDetail"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"exampleJob"</span> /&gt;
    &lt;<span class="hl-comment">!-- run every morning at 6 AM --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"cronExpression"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"0 0 6 * * ?"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>Now we've set up two triggers, one running every 50 seconds with a
      starting delay of 10 seconds and one every morning at 6 AM. To finalize
      everything, we need to set up the
      <code class="classname">SchedulerFactoryBean</code>:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.quartz.SchedulerFactoryBean"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"triggers"</span>&gt;
        &lt;<span class="hl-tag">list</span>&gt;
            &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"cronTrigger"</span> /&gt;
            &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"simpleTrigger"</span> /&gt;
        &lt;<span class="hl-tag">/list</span>&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>More properties are available for the
      <code class="classname">SchedulerFactoryBean</code> for you to set, such as the
      calendars used by the job details, properties to customize Quartz with,
      etc. Have a look at the <a class="ulink" href="http://static.springframework.org/spring/docs/3.0.x/javadoc-api/org/springframework/scheduling/quartz/SchedulerFactoryBean.html" target="_top">SchedulerFactoryBean
      Javadoc</a> for more information.</p></div></div><div class="section" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="scheduling-jdk-timer"></a>26.7&nbsp;Using JDK Timer support</h2></div></div></div><p>The other way to schedule jobs in Spring is to use JDK
    <code class="classname">Timer</code> objects. You can create custom timers or use
    the timer that invokes methods. Wiring timers is done using the
    <code class="classname">TimerFactoryBean</code>.</p><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-jdk-timer-creating"></a>26.7.1&nbsp;Creating custom timers</h3></div></div></div><p>Using the <code class="classname">TimerTask</code> you can create customer
      timer tasks, similar to Quartz jobs:</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> CheckEmailAddresses <span class="hl-keyword">extends</span> TimerTask {

  <span class="hl-keyword">private</span> List emailAddresses;
  
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> setEmailAddresses(List emailAddresses) {
    <span class="hl-keyword">this</span>.emailAddresses = emailAddresses;
  }
  
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> run() {
    <span class="hl-comment">// iterate over all email addresses and archive them</span>
  }
}</pre><p>Wiring it up is simple:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"checkEmail"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"examples.CheckEmailAddress"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"emailAddresses"</span>&gt;
        &lt;<span class="hl-tag">list</span>&gt;
            &lt;<span class="hl-tag">value</span>&gt;test@springframework.org&lt;<span class="hl-tag">/value</span>&gt;
            &lt;<span class="hl-tag">value</span>&gt;foo@bar.com&lt;<span class="hl-tag">/value</span>&gt;
            &lt;<span class="hl-tag">value</span>&gt;john@doe.net&lt;<span class="hl-tag">/value</span>&gt;
        &lt;<span class="hl-tag">/list</span>&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;

&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"scheduledTask"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.timer.ScheduledTimerTask"</span>&gt;
    &lt;<span class="hl-comment">!-- wait 10 seconds before starting repeated execution --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"delay"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"10000"</span> /&gt;
    &lt;<span class="hl-comment">!-- run every 50 seconds --</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"period"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"50000"</span> /&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"timerTask"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"checkEmail"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p><span class="emphasis"><em> Note that letting the task only run once can be done by
      changing the <code class="literal">period</code> property to 0 (or a negative
      value). </em></span></p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-jdk-timer-method-invoking-task"></a>26.7.2&nbsp;Using the
      <code class="classname">MethodInvokingTimerTaskFactoryBean</code></h3></div></div></div><p>Similar to the Quartz support, the <code class="classname">Timer</code>
      support also features a component that allows you to periodically invoke
      a method:</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"doIt"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetObject"</span> <span class="hl-attribute">ref</span>=<span class="hl-value">"exampleBusinessObject"</span> /&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"targetMethod"</span> <span class="hl-attribute">value</span>=<span class="hl-value">"doIt"</span> /&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre><p>The above example will result in the <code class="literal">doIt</code>
      method being called on the <code class="literal">exampleBusinessObject</code> (see
      below):</p><pre class="programlisting"><span class="hl-keyword">public</span> <span class="hl-keyword">class</span> BusinessObject {
  
  <span class="hl-comment">// properties and collaborators</span>
  
  <span class="hl-keyword">public</span> <span class="hl-keyword">void</span> doIt() {
    <span class="hl-comment">// do the actual work</span>
  }
}</pre><p>Changing the <code class="literal">timerTask</code> reference of the
      <code class="classname">ScheduledTimerTask</code> example to the bean
      <code class="literal">doIt</code> will result in the <code class="literal">doIt</code>
      method being executed on a fixed schedule.</p></div><div class="section" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="scheduling-jdk-timer-factory-bean"></a>26.7.3&nbsp;Wrapping up: setting up the tasks using the
      <code class="classname">TimerFactoryBean</code></h3></div></div></div><p>The <code class="classname">TimerFactoryBean</code> is similar to the
      Quartz <code class="classname">SchedulerFactoryBean</code> in that it serves the
      same purpose: setting up the actual scheduling. The
      <code class="classname">TimerFactoryBean</code> sets up an actual
      <code class="classname">Timer</code> and schedules the tasks it has references
      to. You can specify whether or not daemon threads should be used.</p><pre class="programlisting">&lt;<span class="hl-tag">bean</span> <span class="hl-attribute">id</span>=<span class="hl-value">"timerFactory"</span> <span class="hl-attribute">class</span>=<span class="hl-value">"org.springframework.scheduling.timer.TimerFactoryBean"</span>&gt;
    &lt;<span class="hl-tag">property</span> <span class="hl-attribute">name</span>=<span class="hl-value">"scheduledTimerTasks"</span>&gt;
        &lt;<span class="hl-tag">list</span>&gt;
            &lt;<span class="hl-comment">!-- see the example above --</span>&gt;
            &lt;<span class="hl-tag">ref</span> <span class="hl-attribute">bean</span>=<span class="hl-value">"scheduledTask"</span> /&gt;
        &lt;<span class="hl-tag">/list</span>&gt;
    &lt;<span class="hl-tag">/property</span>&gt;
&lt;<span class="hl-tag">/bean</span>&gt;</pre></div></div></div><!--Begin LoopFuse code--><script src="http://loopfuse.net/webrecorder/js/listen.js" type="text/javascript"></script><script type="text/javascript">
			_lf_cid = "LF_48be82fa";
			_lf_remora();
		</script><!--End LoopFuse code--><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="mail.html">Prev</a>&nbsp;</td><td width="20%" align="center"><a accesskey="u" href="spring-integration.html">Up</a></td><td width="40%" align="right">&nbsp;<a accesskey="n" href="dynamic-language.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">25.&nbsp;Email&nbsp;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&nbsp;27.&nbsp;Dynamic language support</td></tr></table></div></body></html>